import { ref, computed } from 'vue'

export interface AudioRecorderState {
  isRecording: boolean
  isSupported: boolean
  audioBlob: Blob | null
  audioUrl: string | null
  duration: number
  error: string | null
}

export function useAudioRecorder() {
  const mediaRecorder = ref<MediaRecorder | null>(null)
  const audioChunks = ref<Blob[]>([])
  const stream = ref<MediaStream | null>(null)
  
  // 检测浏览器支持
  const isSupported = !!(
    navigator.mediaDevices && 
    navigator.mediaDevices.getUserMedia && 
    window.MediaRecorder
  )
  
  const state = ref<AudioRecorderState>({
    isRecording: false,
    isSupported,
    audioBlob: null,
    audioUrl: null,
    duration: 0,
    error: null
  })

  const startTime = ref<number>(0)
  const timer = ref<number | null>(null)

  // 计算录音时长
  const updateDuration = () => {
    if (state.value.isRecording && startTime.value) {
      state.value.duration = Math.floor((Date.now() - startTime.value) / 1000)
    }
  }

  // 开始录音
  const startRecording = async () => {
    if (!isSupported) {
      state.value.error = '您的浏览器不支持录音功能'
      return false
    }

    try {
      // 清理之前的状态
      state.value.error = null
      state.value.audioBlob = null
      state.value.audioUrl = null
      state.value.duration = 0
      audioChunks.value = []

      // 获取音频流
      stream.value = await navigator.mediaDevices.getUserMedia({
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          sampleRate: 16000
        }
      })

      // 创建MediaRecorder
      const options = {
        mimeType: 'audio/webm;codecs=opus'
      }
      
      // 检查浏览器支持的格式
      if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        options.mimeType = 'audio/webm'
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
          options.mimeType = 'audio/mp4'
          if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            delete (options as any).mimeType
          }
        }
      }

      mediaRecorder.value = new MediaRecorder(stream.value, options)

      // 监听数据事件
      mediaRecorder.value.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunks.value.push(event.data)
        }
      }

      // 监听停止事件
      mediaRecorder.value.onstop = () => {
        const audioBlob = new Blob(audioChunks.value, { 
          type: mediaRecorder.value?.mimeType || 'audio/webm' 
        })
        state.value.audioBlob = audioBlob
        state.value.audioUrl = URL.createObjectURL(audioBlob)
        state.value.isRecording = false
        
        // 停止定时器
        if (timer.value) {
          clearInterval(timer.value)
          timer.value = null
        }
      }

      // 开始录音
      mediaRecorder.value.start(100) // 每100ms收集一次数据
      state.value.isRecording = true
      startTime.value = Date.now()
      
      // 开始计时器
      timer.value = setInterval(updateDuration, 1000)

      return true
    } catch (error) {
      console.error('录音启动失败:', error)
      state.value.error = '录音启动失败，请检查麦克风权限'
      return false
    }
  }

  // 停止录音
  const stopRecording = (): Promise<Blob | null> => {
    return new Promise((resolve) => {
      if (mediaRecorder.value && state.value.isRecording) {
        const onStop = () => {
          mediaRecorder.value?.removeEventListener('stop', onStop)
          resolve(state.value.audioBlob)
        }
        
        mediaRecorder.value.addEventListener('stop', onStop)
        mediaRecorder.value.stop()
        
        // 停止音频流
        if (stream.value) {
          stream.value.getTracks().forEach(track => track.stop())
          stream.value = null
        }
      } else {
        resolve(null)
      }
    })
  }

  // 清理资源
  const cleanup = () => {
    if (state.value.audioUrl) {
      URL.revokeObjectURL(state.value.audioUrl)
    }
    
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
    
    if (stream.value) {
      stream.value.getTracks().forEach(track => track.stop())
      stream.value = null
    }
    
    state.value.audioBlob = null
    state.value.audioUrl = null
    state.value.duration = 0
    state.value.error = null
    audioChunks.value = []
  }

  // 转换为Base64
  const toBase64 = (): Promise<string> => {
    return new Promise((resolve, reject) => {
      if (!state.value.audioBlob) {
        reject(new Error('没有录音数据'))
        return
      }

      const reader = new FileReader()
      reader.onload = () => {
        const result = reader.result as string
        const base64 = result.split(',')[1] // 移除data:audio/webm;base64,前缀
        resolve(base64)
      }
      reader.onerror = reject
      reader.readAsDataURL(state.value.audioBlob)
    })
  }

  // 格式化时长显示
  const formatDuration = computed(() => {
    const minutes = Math.floor(state.value.duration / 60)
    const seconds = state.value.duration % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  })

  return {
    state: computed(() => state.value),
    isSupported,
    startRecording,
    stopRecording,
    cleanup,
    toBase64,
    formatDuration
  }
}